<template>
	<!-- 页面结构 -->
	<view class="u-wrap">
		<!-- 搜索框 -->
		<view class="u-search-box">
			<view class="u-search-inner">
				<up-icon name="search" color="#909399" :size="28"></up-icon>
				<text class="u-search-text">搜索(暂时关闭)</text>
			</view>
		</view>
		<!-- 菜单栏和内容区域 -->
		<view class="u-menu-wrap">
			<!-- 左侧菜单栏 -->
			<scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view" :scroll-top="scrollTop"
				:scroll-into-view="itemId">
				<view v-for="(item, index) in tabbar" :key="item.id" class="u-tab-item"
					:class="[current == index ? 'u-tab-item-active' : '']" @tap.stop="swichMenu(index)">
					<text class="u-line-1">{{item.categoryName}}</text>
				</view>
			</scroll-view>
			<!-- 右侧内容区域 -->
			<scroll-view :scroll-top="scrollRightTop" scroll-y scroll-with-animation class="right-box"
				@scroll="rightScroll">
				<view class="page-view">
					<view class="class-item" :id="'item' + index" v-for="(item , index) in tabbar" :key="item.id">
						<view class="item-title">
							<text style="color: #2684ff;">{{item.categoryName}}</text>
						</view>
						<view class="item-container">
							<view class="thumb-box" v-for="(item1, index1) in item.children" :key="item1.id"
								@tap="onClick(item,item1)">
								<image class="item-menu-image" src="https://peixin.peiyu.online/xmk/images/测试图.png"
									mode=""></image>
								<view class="item-menu-name">{{item1.categoryName}}</view>
								<view class="item-menu-name" style="color: chocolate;">{{item1.standardPrice}}</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		nextTick,
		unref,
	} from 'vue';
	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app";
	import {
		api_serviceCategory_get_by_service,
		api_serviceItem_add,
	} from "../../../../apis/apis.js";
	import {
		useMainStore
	} from '@/utils/store.js';

	const scrollTop = ref(0); // 左侧菜单栏的滚动条位置
	const current = ref(0); // 当前选中的菜单项索引
	const itemId = ref(''); // 右侧内容区滚动定位ID
	const tabbar = ref([]); // 分类数据
	const menuItemPos = []; // 菜单项位置数组
	const arr = []; // 记录每个内容区块的位置
	const scrollRightTop = ref(0); // 右侧内容区的滚动条高度
	const timer = ref(null); // 用于防止滚动事件重复触发的定时器
	const store = ref(useMainStore()); //状态存储
	const orderServiceId = ref(0);
	const serviceName = ref("")
	const servicePrice = ref("")
	const serviceItemId = ref(0)

	// 初始化
	onLoad(async (e) => {
		orderServiceId.value = e.orderServiceId;
		//分类数据
		try {
			await get_classifyData();
		} catch (e) {
			uni.showToast({
				title: e.msg,
				icon: "none"
			});
		}
		//获取菜单项位置
		try {
			await getMenuItemTop();
		} catch (e) {
			uni.showToast({
				title: e.msg,
				icon: "none"
			});
		}

	});

	// 切换左侧菜单项
	const swichMenu = async (index) => {
		if (arr.length === 0) {
			await getMenuItemTop();
		}
		if (index === current.value) return;
		scrollRightTop.value = scrollTop.value;
		nextTick(() => {
			scrollRightTop.value = arr[index]; // 滚动到对应的内容区块
			current.value = index;
			leftMenuStatus(index); // 更新左侧菜单栏状态
		});
	};

	// 获取元素的高度
	const getElRect = (elClass) => {
		return new Promise((resolve) => {
			const query = uni.createSelectorQuery();
			query.select(`.${elClass}`).boundingClientRect((rect) => {
				resolve(rect.height); // 直接返回高度值
			}).exec();
		});
	};

	// 观察右侧内容区块的可见性
	const observer = () => {
		unref(tabbar).forEach((val, index) => {
			const observer = uni.createIntersectionObserver(this);
			observer.relativeTo('.right-box', {
				top: 0
			}).observe(`#item${index}`, (res) => {
				if (res.intersectionRatio > 0) {
					leftMenuStatus(res.id.substring(4)); // 更新左侧菜单栏状态
				}
			});
		});
	};

	// 更新左侧菜单栏的状态
	const leftMenuStatus = async (index) => {
		current.value = index;
		if (unref(menuItemHeight) === 0 || unref(menuHeight) === 0) {
			await Promise.all([
				getElRect('menu-scroll-view').then(height => menuHeight.value = height),
				getElRect('u-tab-item').then(height => menuItemHeight.value = height)
			]);
		}
		scrollTop.value = index * unref(menuItemHeight) + unref(menuItemHeight) / 2 - unref(menuHeight) / 2;
	};

	// 获取每个内容区块的顶部位置
	const getMenuItemTop = () => {
		new Promise((resolve) => {
			let selectorQuery = uni.createSelectorQuery();
			selectorQuery.selectAll('.class-item').boundingClientRect((rects) => {
				if (!rects.length) {
					setTimeout(() => {
						getMenuItemTop();
					}, 10);
					return;
				}
				rects.forEach((rect) => {
					arr.push(rect.top - rects[0].top);
				});
				resolve();
			}).exec();
		});
	};

	// 右侧内容区滚动事件处理
	const rightScroll = (e) => {
		if (timer.value) return;
		if (!arr.length) {
			getMenuItemTop();
		}
		if (!unref(menuHeight)) {
			getElRect('menu-scroll-view').then(height => menuHeight.value = height);
		}
		setTimeout(() => {
			timer.value = null;
			let scrollHeight = e.detail.scrollTop + unref(menuHeight) / 2;
			for (let i = 0; i < arr.length; i++) {
				let height1 = arr[i];
				let height2 = arr[i + 1];
				if (!height2 || scrollHeight >= height1 && scrollHeight < height2) {
					leftMenuStatus(i);
					return;
				}
			}
		}, 10);
	};

	// 高度变量
	const menuHeight = ref(0);
	const menuItemHeight = ref(0);

	// 点击事件处理
	const onClick = async (item, item1) => {
		if (store.value.serviceItem.some(item => item.serviceName == item1.categoryName)) { //服务有没有已经选择过
			uni.showToast({
				title: "已经选过了",
				icon: "error"
			});
			return;
		} else {
			let res = await api_serviceItem_add({ //上传服务
				orderServiceId: parseInt(orderServiceId.value),
				name: item1.categoryName,
				standardPrice: item1.standardPrice ? item1.standardPrice : 0,
				actualPrice: item1.standardPrice ? item1.standardPrice : 0,
			});
			store.value.set_serviceItem({ //把服务项目存到pinia
				serviceName: item1.categoryName,
				servicePrice: item1.standardPrice ? item1.standardPrice : 0,
				productName: '',
				productPrice: 0,
				serviceItemId: res.data.serviceItemId
			});
			if (item1.standardPrice > 0 || item1.standardPrice != undefined || item1.standardPrice !=
				null) { // 有下一级，就继续，没有就返回
				store.value.serviceItem[0].flag = false; //falg不用删除
				uni.navigateBack({
					delta: 1
				});
			} else {
				store.value.serviceItem[0].flag = true; //falg要删除
				serviceItemId.value = res.data.serviceItemId;
				uni.navigateTo({
					url: `/pages/salesman/new-order/product_classify/product_classify?serverCgId=${item.id}&orderServiceId=${orderServiceId.value}&serviceItemId=${serviceItemId.value}`,
				});
			}
		}
	};

	//加载数据
	const get_classifyData = async () => {
		let res = await api_serviceCategory_get_by_service();
		console.log("分类内容", res);
		tabbar.value = res.data;
	}
</script>

<style lang="scss" scoped>
	.u-wrap {
		width: 750rpx;
		height: 100vh;
		/* #ifdef H5 */
		height: calc(100vh - var(--window-top));
		/* #endif */
		display: flex;
		flex-direction: column;
	}

	.u-search-box {
		padding: 18rpx 30rpx;
	}

	.u-menu-wrap {
		flex: 1;
		display: flex;
		overflow: hidden;
	}

	.u-search-inner {
		background-color: rgb(234, 234, 234);
		border-radius: 100rpx;
		display: flex;
		align-items: center;
		padding: 10rpx 16rpx;
	}

	.u-search-text {
		font-family: Alibaba_PuHuiTi_Light;
		font-weight: 300;
		font-size: 26rpx;
		color: $u-tips-color;
		margin-left: 10rpx;
	}

	.u-tab-view {
		width: 200rpx;
		height: 100%;
	}

	.u-tab-item {
		font-family: Alibaba_PuHuiTi_Regular;
		font-weight: 400;
		height: 110rpx;
		background: #f6f6f6;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 26rpx;
		color: #444;
		line-height: 1;
	}

	.u-tab-item-active {
		font-family: Alibaba_PuHuiTi_Medium;
		font-weight: 500;
		position: relative;
		color: #000;
		font-size: 30rpx;
		background: #fff;
	}

	.u-tab-item-active::before {
		content: "";
		position: absolute;
		border-left: 4px solid $u-primary;
		height: 32rpx;
		left: 0;
		top: 39rpx;
	}

	.u-tab-view {
		height: 100%;
	}

	.right-box {
		background-color: rgb(250, 250, 250);
	}

	.page-view {
		padding: 16rpx;
	}

	.class-item {
		margin-bottom: 30rpx;
		background-color: #fff;
		padding: 16rpx;
		border-radius: 8rpx;
	}

	.class-item:last-child {
		min-height: 100vh;
	}

	.item-title {
		font-family: Alibaba_PuHuiTi_Regular;
		font-weight: 400;
		font-size: 26rpx;
		color: $u-main-color;
	}

	.item-menu-name {
		font-family: Alibaba_PuHuiTi_Light;
		font-weight: 300;
		font-size: 30rpx;
		color: $u-main-color;
	}

	.item-container {
		display: flex;
		flex-wrap: wrap;
	}

	.thumb-box {
		width: 33.333333%;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		margin-top: 20rpx;
	}

	.item-menu-image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 100rpx;
		overflow: hidden;
	}
</style>